package com.neusoft.ecommerce.dbhelper;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.stream.IntStream;

/**
 * @author 紫煦桉
 */
public class VerifyCode {

    private static final int NUM = 4;

    public static  String drawRandomText(int width, int height, BufferedImage verifyImg) {
        Graphics2D graphics = (Graphics2D)verifyImg.getGraphics();
        //设置画笔颜色-验证码背景色
        graphics.setColor(Color.WHITE);
        //填充背景
        graphics.fillRect(0, 0, width, height);
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 24));
        //数字和字母的组合
        String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        StringBuilder sBuffer = new StringBuilder();
        //旋转原点的 x 坐标
        int x = 4;
        Random random = new Random();
        for(int i = 0;i < NUM;i++){
            graphics.setColor(getRandomColor());
            //设置字体旋转角度 角度小于30度
            int degree = random.nextInt() % 30;
            int dot = random.nextInt(baseNumLetter.length());
            String ch = baseNumLetter.charAt(dot) + "";
            sBuffer.append(ch);
            //正向旋转
            graphics.rotate(degree * Math.PI / 180, x, 25);
            graphics.drawString(ch, x, 25);
            //反向旋转
            graphics.rotate(-degree * Math.PI / 180, x, 25);
            x += 18;
        }
        //画干扰线
        // 设置随机颜色
        // 随机画线
        IntStream.range(0, 6).forEach(i -> {
            graphics.setColor(getRandomColor());
            graphics.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        });
        //添加噪点
        IntStream.range(0, 30).map(i -> random.nextInt(width)).forEach(x1 -> {
            int y1 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.fillRect(x1, y1, 2, 2);
        });
        System.out.println(sBuffer.toString());
        return sBuffer.toString();
    }
    private static Color getRandomColor() {
        Random ran = new Random();
        return new Color(ran.nextInt(256),
                ran.nextInt(256), ran.nextInt(256));
    }
}
